import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const list = JSON.parse(localStorage.getItem('cartArray')) || []
let store = new Vuex.Store({
  state: {
    token: '',
    cartArray: list
  },
  mutations: {
    settoken (state, token) {
      if (token) {
        state.token = token
        localStorage.setItem('token', token)
      }
    },
    setCart (state, cart) {
      let goods = state.cartArray.find(v => v.title === cart.title)
      console.log(cart)
      if (goods) {
        goods.cartCount += 1
      } else {
        state.cartArray.push({
          title: cart.title,
          cartCount: 1,
          image: cart.image
        })
      }
    },
    cartAdd (state, index) {
      state.cartArray[index].cartCount++
    },
    cartRemove (state, index) {
      if (state.cartArray[index].cartCount > 1) {
        state.cartArray[index].cartCount--
      } else {
        state.cartArray.splice(index, 1)
      }
    },
    emptyCartArray (state) {
      state.cartArray = []
      localStorage.removeItem('cartArray')
    }
  },
  actions: {

  },
  getters: {
    getCartArray (state) {
      return state.cartArray
    },
    getCount (state) {
      let Count = 0
      state.cartArray.forEach(val => {
        Count += val.cartCount
      })
      console.log(Count)
      return Count
    }
  }
})
store.subscribe((mutation, state) => {
  // 每次 mutation 之后调用
  // mutation 的格式为 { type, payload }
  // console.log(state.cartArray)
  localStorage.setItem('cartArray', JSON.stringify(state.cartArray))
})
export default store
